package com.nextbusmn.server.JDOWrappers;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.nextbusmn.server.dataobjects.NextBusData;
import com.nextbusmn.server.dataobjects.ShapeData;


public class ShapeJDOWrapper extends JDOWrapper {

	public ShapeJDOWrapper(ShapeData data) {
		this.setData(data);
	}
	
	@Override
	public boolean dataExists(NextBusData data) {
		ShapeData id = getByShapeIDAndSequence(((ShapeData) data).getShapeID(),
				((ShapeData) data).getShapePtSequence());
		return id != null;
	}
	
	public static ShapeData getByShapeIDAndSequence(int id, long seq) {
		PersistenceManager pm = getPersistenceManagerFactory().getPersistenceManager();
		
		Query query = pm.newQuery(ShapeData.class);
		query.setFilter("shapeID == IDParam && shapePtSequence == seqParam");
		query.declareParameters("int IDParam, long seqParam");

		List<ShapeData> result = null;
		
		try {
			result = (List<ShapeData>) query.execute(id, seq);
		} finally {
			query.closeAll();
		}
		
		if (result.size() > 1) {
			System.out.println("Data problem: Key not unique!"); 
		}
		
		return result.size() == 1 ? result.get(0) : null;
	}
	
	public static List<ShapeData> getAllRows() {
		return (List<ShapeData>) JDOWrapper.getAllRows(ShapeData.class);
	}

	public static List<ShapeData> getShapesByID(int shapeID) {
		PersistenceManager pm = getPersistenceManagerFactory().getPersistenceManager();
		
		Query query = pm.newQuery(ShapeData.class);
		query.setFilter("shapeID == IDParam");
		query.declareParameters("int IDParam");
		query.setOrdering("shapePtSequence ascending");
		
		List<ShapeData> result = null;
		
		try {
			result = (List<ShapeData>) query.execute(shapeID);
		} finally {
			query.closeAll();
		}
		
		return result;
	}
}
